package com.gouwudai.gobbs.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.buffalo.request.RequestContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.extremecomponents.table.limit.Limit;

import com.gouwudai.gobbs.common.AjaxReturn;
import com.gouwudai.gobbs.common.Constants;
import com.gouwudai.gobbs.common.IPageList;
import com.gouwudai.gobbs.dao.IClassPermissionDAO;
import com.gouwudai.gobbs.dao.IClassUserDAO;
import com.gouwudai.gobbs.dao.IFriendsDAO;
import com.gouwudai.gobbs.dao.IRegCounterDAO;
import com.gouwudai.gobbs.dao.IRuleDAO;
import com.gouwudai.gobbs.dao.ISysInfoDAO;
import com.gouwudai.gobbs.dao.IUserDAO;
import com.gouwudai.gobbs.pojo.TbbsClassPermission;
import com.gouwudai.gobbs.pojo.TbbsPermission;
import com.gouwudai.gobbs.pojo.TbbsRule;
import com.gouwudai.gobbs.pojo.TbbsSysInfo;
import com.gouwudai.gobbs.pojo.TbbsUserDetail;
import com.gouwudai.gobbs.pojo.TbbsUserInfo;
import com.gouwudai.gobbs.service.IUserService;
import com.gouwudai.gobbs.vo.UserLoginVO;
import com.litt.core.common.PageParam;
import com.litt.core.common.Utility;
import com.litt.core.exception.BusiException;
import com.litt.core.exception.DBException;
import com.litt.core.exception.NotLoginException;
import com.litt.core.mail.SendEmail;
import com.litt.core.tools.beanutils.BeanUtilsEx;
import com.litt.core.util.ExtremeTableUtil;
import com.litt.core.util.FormatDateTime;
import com.litt.core.util.ParamUtils;
import com.litt.core.util.html.EncodeString;

public class UserServiceImpl implements IUserService 
{
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(UserServiceImpl.class);

	IUserDAO userDAO;	
	IRuleDAO ruleDAO;
	IRegCounterDAO regCounterDAO;
	ISysInfoDAO sysInfoDAO;
	IFriendsDAO friendsDAO;
    IClassUserDAO classUserDAO;
    IClassPermissionDAO classPermissionDAO;
	
	/**
	 * 用户注册
	 * @param params
	 * @return
	 */
	public void doUserReg(HashMap userInfoMap,HashMap userDetailMap,Boolean saveDetailFlag) throws BusiException
	{
			//验证用户是否已被注册 - START
			int count = userDAO.countByLoginId(ParamUtils.getMapToString(userInfoMap, "loginId"));
			if(count>0)
				throw new BusiException("该登陆ID已被注册！");
			//验证用户是否已被注册 - END
			
			TbbsUserInfo tbbsUserInfo = new TbbsUserInfo();
			TbbsUserDetail tbbsUserDetail = new TbbsUserDetail();
			BeanUtilsEx.copyProperties(tbbsUserInfo, userInfoMap);	
			//一些默认属性的添加			 
			tbbsUserInfo.setRegTime(new Date());
			tbbsUserInfo.setLoginTimes(new Integer(0));
			tbbsUserInfo.setOnlineTime(new Integer(0));
			tbbsUserInfo.setUserTopicCount(new Integer(0));
			tbbsUserInfo.setUserReCount(new Integer(0));
			tbbsUserInfo.setIsdelFlag(false);
			tbbsUserInfo.setUpfileOpenFlag(true);
			tbbsUserInfo.setUpfileSize(new Integer(5000));//5M
			tbbsUserInfo.setUpfileUsedSize(new Integer(0));
			tbbsUserInfo.setPicOpenFlag(true);
			tbbsUserInfo.setGradeId(new Integer(3));	//注册用户
			//可以再通过审核、检测邮件地址等信息将用户等级变更为	//诚信用户
			
			//获取注册用户级别注册时获得的积分信息			
			TbbsRule tbbsRule = ruleDAO.loadByCode("R015");
			tbbsUserInfo.setUserCredit(tbbsRule.getRuleCredit());
			tbbsUserInfo.setUserDeposit(tbbsRule.getRuleDeposit());
			tbbsUserInfo.setUserMark(tbbsRule.getRuleMark());
			tbbsUserInfo.setUserMoney(tbbsRule.getRuleMoney());
			
            int userId = userDAO.saveUserInfo(tbbsUserInfo);            
			if(saveDetailFlag)
			{
				BeanUtilsEx.copyProperties(tbbsUserDetail, userDetailMap);					
				//设置附加参数
				//tbbsUserDetail.setBirthday(FormatDateTime.formatDateInteger(Utility.parseDate(params.get("birthday").toString())));
				//tbbsUserDetail.setMobile(params.get("mobile").toString());
				//tbbsUserDetail.setTelephone(params.get("telephone").toString());
				//tbbsUserDetail.setAddress(params.get("address").toString());
				//tbbsUserDetail.setPostNo(Utility.parseInt(params.get("postNo").toString()));
				//tbbsUserDetail.setQq(params.get("qq").toString());
				//tbbsUserDetail.setMsn(params.get("msn").toString());
				//tbbsUserDetail.setJob(params.get("job").toString())				
			}
			tbbsUserDetail.setUserId(userId);
			userDAO.saveUserDetail(tbbsUserDetail);	
			//更新统计信息 START			
			String sex = tbbsUserInfo.getSex();
			int boy=0,girl=0,secret=0;
			if(sex.equals("M"))
				boy = 1;
			else if(sex.equals("F"))
				girl = 1;
			else
				secret = 1;
			regCounterDAO.updateUserModify(boy, girl, secret, true, tbbsUserInfo.getUserName());
			//更新统计信息 END
	}
	
	/**
     * 用户修改注册信息.
     * 
     * @param userDetailMap 用户详细信息相关属性
     * @param userInfoMap  用户基本信息相关属性
     * @param saveDetailFlag 是否保存用户详细信息标志
     */
	public void updateUser(HashMap userInfoMap,HashMap userDetailMap,Boolean saveDetailFlag) throws BusiException
	{
			int userId = ParamUtils.getMapToInt(userInfoMap, "userId");
            if(userId<=0)
                 throw new BusiException("用户尚未登陆！");   
			TbbsUserInfo tbbsUserInfo = userDAO.load(userId);
			TbbsUserDetail tbbsUserDetail = userDAO.loadDetail(userId);
			
			String sex = ParamUtils.getMapToString(userInfoMap, "sex");
			String sexOld = tbbsUserInfo.getSex();
			String password  = ParamUtils.getMapToString(userInfoMap, "password");
			if(!password.equals(""))
			{	
				//加密密码		
				String md5Pass = Utility.MD5EncodeString(password);	
				tbbsUserInfo.setPassword(md5Pass);
			}	
			tbbsUserInfo.setSex(ParamUtils.getMapToString(userInfoMap, "sex"));
			tbbsUserInfo.setEmail(ParamUtils.getMapToString(userInfoMap, "email"));
			tbbsUserInfo.setEmailOpenFlag(ParamUtils.getMapToString(userInfoMap, "emailOpenFlag"));
			tbbsUserInfo.setPersonalSign(ParamUtils.getMapToString(userInfoMap, "personalSign"));
			tbbsUserInfo.setPersonalIntro(ParamUtils.getMapToString(userInfoMap, "personalIntro"));			
			
			if(saveDetailFlag)
			{
				tbbsUserInfo.setTrueName(ParamUtils.getMapToString(userDetailMap, "trueName"));
				Date birthday = ParamUtils.getMapToDate(userDetailMap, "birthday");
                if(birthday!=null)
                    tbbsUserDetail.setBirthday(FormatDateTime.formatDateInteger(birthday));
				tbbsUserDetail.setPersonalWeb(ParamUtils.getMapToString(userDetailMap, "personalWeb"));
				tbbsUserDetail.setMobile(ParamUtils.getMapToString(userDetailMap, "mobile"));
				tbbsUserDetail.setTelephone(ParamUtils.getMapToString(userDetailMap, "telephone"));
				tbbsUserDetail.setAddress(ParamUtils.getMapToString(userDetailMap, "address"));
				tbbsUserDetail.setPostNo(ParamUtils.getMapToInteger(userDetailMap, "postNo"));
				tbbsUserDetail.setArea(ParamUtils.getMapToString(userDetailMap, "area"));
				tbbsUserDetail.setCity(ParamUtils.getMapToString(userDetailMap, "city"));
				tbbsUserDetail.setQq(ParamUtils.getMapToString(userDetailMap, "qq"));
				tbbsUserDetail.setMsn(ParamUtils.getMapToString(userDetailMap, "msn"));
				tbbsUserDetail.setJob(ParamUtils.getMapToString(userDetailMap, "job"));			
				userDAO.updateUserDetail(tbbsUserDetail);
			}	
			userDAO.updateUserInfo(tbbsUserInfo);
			//如果用户修改了性别
			if(!sex.equals(sexOld))
			{
				//更新统计信息 START				
				int boy=0,girl=0,secret=0;
				if(sex.equals("M"))
					boy = 1;
				else if(sex.equals("F"))
					girl = 1;
				else
					secret = 1;
				if(sexOld.equals("M"))
					boy = -1;
				else if(sexOld.equals("F"))
					girl = -1;
				else
					secret = -1;
				
				regCounterDAO.updateUserModify(boy, girl, secret, false, tbbsUserInfo.getUserName());				
				//更新统计信息 END
			}	
	}	
	
	/**
	 * 根据用户名读取用户信息
	 * @param userId  用户ID
	 * @return TbbsUserInfo
	 */
	public TbbsUserInfo load(Integer userId)
	{
		return userDAO.load(userId);
	}
	
	/**
	 * 读取用户详细信息
	 * @param userId 用户ID
	 * @return TbbsUserDetail
	 */
	public TbbsUserDetail loadDetail(Integer userId)  
	{
		return userDAO.loadDetail(userId);
	}
	
	/**
	 * 后台管理员更新用户积分、金币，用户空间等信息
	 * @param params 相关参数
	 */
	public void updateAdmin(HashMap params)
	{
			TbbsUserInfo tbbsUserInfo = new TbbsUserInfo();
			com.litt.core.tools.beanutils.BeanUtilsEx.copyProperties(tbbsUserInfo, params);
			userDAO.updateAdmin(tbbsUserInfo);
	}	
	
   /**
    * 更新用户密码
    * @param password 新密码
    * @param userId 用户ID
    */
	public void updatePassword(String password,Integer userId)
	{
			userDAO.updatePassword(password, userId);
	}	
	
	/**
     * 更新个人空间已使用大小.
     * 
     * @param userId 用户ID
     * @param upfileSize 上传文件的大小
     * 
     * @return int 剩余空间大小
     */
    public int updateUpfileUsedSize(Integer upfileSize,Integer userId)
    {
        TbbsUserInfo tbbsUserInfo = userDAO.load(userId); 
        int upfileUserSize = tbbsUserInfo.getUpfileUsedSize().intValue()+upfileSize;
        userDAO.updateUpfileUsedSize(new Integer(upfileUserSize),userId);
        int remainSize = tbbsUserInfo.getUpfileSize().intValue() - upfileUserSize;  //剩余空间大小
        return remainSize;
	}	
    
    /**
     * 更新用户头像.
     * 
     * @param personalPic 用户头像路径
     * @param userId 用户ID
     */
    public void updatePersonalPic(String personalPic,Integer userId)
    {   
			userDAO.updatePersonalPic(personalPic,userId);
    }
	
	/**
	 * 逻辑删除用户
	 * @param userId
	 * @return
	 * @throws DBException
	 */
	public void deleteLogic(Integer userId)
	{
			userDAO.deleteLogic(userId);
	}
	
	/**
	 * 逻辑恢复用户
	 * @param userId
	 * @return
	 * @throws DBException
	 */
	public void doResumeLogic(Integer userId)
	{
			userDAO.doResumeLogic(userId);
	}	

	/**
	 * 物理删除用户，该方法不推荐使用，目前也不使用，用户都是逻辑删除
	 * @param userId
	 * @return
	 * @throws DBException
	 */
	public void delete(Integer userId)
	{
			userDAO.delete(userId);
			//更新统计信息 START 需修改性别统计信息
			
			//更新统计信息 END
	}
	
    /**
     * 根据用户名、密码问题和密码答案找到对应用户并生成新密码.
     * 
     * @param passQuestion 密码问题
     * @param loginId 用户登陆ID
     * @param passAnswer 密码答案
     * 
     * @throws BusiException
     */
    public void findPass(String loginId,String passQuestion,String passAnswer) throws BusiException
    {
			//查找用户
			TbbsUserInfo tbbsUserInfo = userDAO.load(loginId);
			int userId = tbbsUserInfo.getUserId();
			//验证密码提示问题和答案
			if(!tbbsUserInfo.getPassQuestion().equals(passQuestion)||!tbbsUserInfo.getPassAnswer().equals(passAnswer))
			{
				throw new BusiException("密码提示问题或答案错误，请重新尝试或向管理员求助！");
			}
			//取随机产生6位数字字母混排的密码
			String choose = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";			
			Random random = new Random();
			char[] sRand = {'0','0','0','0','0','0'};
			char temp;
			for (int i = 0; i < 6; i++) 
			{				
				temp=choose.charAt(random.nextInt(choose.length()));			
				sRand[i]= temp;
			}					
			//发送邮件
			try
			{
				//获取系统邮件服务器信息				
				TbbsSysInfo tbbsSysInfo = sysInfoDAO.load();
				String smtpId = tbbsSysInfo.getSmtpId();
				String smtpPass =  tbbsSysInfo.getSmtpPass();
				String sysEmail = tbbsSysInfo.getSysEmail();
				String sysEmailSign = tbbsSysInfo.getSysEmailSign();
				String smtpServer = tbbsSysInfo.getSmtpServer();
				int smtpPort = Utility.parseInt(tbbsSysInfo.getSmtpPort(),25);
				boolean smtpAuth = tbbsSysInfo.getSmtpAuth().booleanValue();
				boolean smtpSsl = tbbsSysInfo.getSmtpSsl().booleanValue();
				SendEmail sendEmail = new SendEmail();
				sendEmail.setSmtpServer(smtpServer);
				sendEmail.setSmtpPort(smtpPort);
				sendEmail.setSmtpUser(smtpId);
				sendEmail.setSmtpPwd(smtpPass);
				sendEmail.setNeedAuth(smtpAuth);
				sendEmail.setNeedSSL(smtpSsl);
				sendEmail.setMailFrom(sysEmail);
				sendEmail.setMailSign(sysEmailSign);
				sendEmail.setMailTo(tbbsUserInfo.getEmail());
				sendEmail.setTtitle(tbbsSysInfo.getSysName()+"系统邮件 - 找回密码");
				sendEmail.setTcontent("您的新密码为："+String.valueOf(sRand)+",请妥善保管！");
				sendEmail.sendMail();
			}
			catch(Exception e)
			{
				throw new BusiException("发送邮件失败，请确认您的邮件地址！",e);
			}			
			//发送邮件成功后再修改密码
			userDAO.updatePassword(String.valueOf(sRand), userId);	
    }

	/**
	 * 查询所有有效用户
	 * @return
	 */
    public List listAllActive()
    { 
    	return userDAO.listAllActive();
    }
    
    /**
     * 查询所有不是指定版面黑名单的有效用户.
     * 
     * @param classId 版面ID
     * 
     * @return the list
     */
    public List listAllClassActive(Integer classId)
    {
        return userDAO.listAllClassActive(classId); 
    }
    
    /**
     * 查询指定版面黑名单用户.
     * 
     * @param classId 版面ID
     * 
     * @return the list
     */
    public List listAllClassBlack(Integer classId)
    {
        return userDAO.listAllClassBlack(classId);
    }
    
	/**
	 * 查询所有等级为gradeId的有效用户
	 * @param gradeId
	 * @return
	 */
    public List listAllActiveByGrade(int gradeId)
    { 
    	return userDAO.listAllActiveByGrade(gradeId);
    }
    
	/**
	 * 查询所有等级为gradeIds的有效用户
	 * @param gradeIds
	 * @return
	 */
    public List listAllActiveByGrade(String gradeIds)
    {
    	return userDAO.listAllActiveByGrade(gradeIds);
    }

	public IPageList listPage(PageParam pageParam)
	{
		return userDAO.listPage(pageParam);
	}
	
	public void AutoBindingTable(javax.servlet.http.HttpServletRequest request)
	{
		Map<String,Object> conds = new HashMap<String,Object>(5);
        conds.put("loginId", request.getParameter("loginId"));
        conds.put("userName", request.getParameter("userName"));
        conds.put("trueName", request.getParameter("trueName"));
        conds.put("email", request.getParameter("email"));
        conds.put("gradeId", request.getParameter("gradeId"));
		Limit limit = ExtremeTableUtil.getLimit(request, Constants.DEFAULT_PAGE_SIZE);
        IPageList page = this.listPage(new PageParam(conds,limit.getPage(), limit.getCurrentRowsDisplayed(),ExtremeTableUtil.getSort(limit)));
		request.setAttribute("resultList",page.getRsList());
		request.setAttribute("totalRows",page.getTotalSize());
	}	
	
//	public void AutoBinding(HttpServletRequest request)
//	{
//		TbbsUserInfo tbbsUserInfo = new TbbsUserInfo();		
//		ParamUtils.DynaBinder(tbbsUserInfo,request);	//动态绑定request值到对象中		
//	}	
//	
    /**
     * @param loginId 用户名
     * @param password 密码
     * @param loginIp 登陆IP
     * @return UserLoginVO
     * @throws BusiException
     */
	public UserLoginVO doUserLogin(String loginId,String password,String loginIp) throws BusiException
	{
		logger.info("用户 "+loginId+" 尝试登陆,登陆IP："+loginIp);
		TbbsUserInfo tbbsUserInfo = (TbbsUserInfo)userDAO.load(loginId);        
		//判断登陆名
		if(tbbsUserInfo==null)
			throw new NotLoginException("用户名不存在！");		
		String md5Pass = Utility.MD5EncodeString(password);		
		//判断密码
		if(!tbbsUserInfo.getPassword().equals(md5Pass))
			throw new NotLoginException("密码错误！");
		//更新管理员登陆相关信息
        Integer userId = tbbsUserInfo.getUserId();
		UserLoginVO vo = new UserLoginVO();
		String lastLoginIp = tbbsUserInfo.getLastLoginIp();		
		Date lastLoginTime = tbbsUserInfo.getLastLoginTime();
		userDAO.doLoginUpdate(userId,loginIp);
		//更新我的好友中的在线状态		
		friendsDAO.updateOnline(loginId, true);
		//将对象属性设到VO中，并存入SESSION		
		ParamUtils.DynaBinder(vo,tbbsUserInfo);
		vo.setLastLoginTime(lastLoginTime);
		vo.setLastLoginIp(lastLoginIp);
		vo.setLoginIp(loginIp);	//当前登陆IP
		//查询登陆用户的权限		
		List list = userDAO.getGradePermission(tbbsUserInfo.getGradeId());
		
		TbbsPermission tbbsPermission = null;		
		for(int i=0;i<list.size();i++)
		{			
			tbbsPermission = (TbbsPermission)list.get(i);			
			vo.addPermission(tbbsPermission.getPermissionCode(), tbbsPermission.getPermissionName());
		}
		//查询登陆用户拥有的分类/版面权限       
        List classPermissionList = classPermissionDAO.listAllPermission(userId);
        
        TbbsClassPermission tbbsClassPermission = null;       
        for(int i=0;i<classPermissionList.size();i++)
        {           
            Object[] objs = (Object[])classPermissionList.get(i);
            tbbsClassPermission = (TbbsClassPermission)objs[0];           
            vo.addClassPermission(tbbsClassPermission.getClassId(), tbbsClassPermission.getPermissionCode(), objs[1].toString());
        }
        //查询用户被认证过的分类/版面
        //List authClass = classUserDAO.listAuthUserClass(userId);
        
		return vo;
	}	
	
	/**
	 * 判断Cookie中是否保存用户名密码
	 * @param cookies
	 * @param loginIp
	 * @throws BusiException
	 */
	public UserLoginVO userLogin(Cookie[] cookies,String loginIp) throws BusiException
	{
		String loginId = "";
		String password = "";
		
		if (cookies!=null)
		{
			for (int i = 0; i < cookies.length; i++)
			{
				Cookie c = cookies[i];
				String name = c.getName().trim();
				String value = c.getValue().trim();
				
				if(name.equals("U_LOGIN_ID"))
				{
					loginId = value;
				}
				if(name.equals("U_PASSWORD")){
					password = value;
				}
			}
		}
		if(loginId.equals("")||password.equals(""))
			throw new NotLoginException("");
		return doUserLogin(loginId,password,loginIp);
	}
	
	/**
	 * 游客方式登陆
     * @param loginIp 登陆IP
     * @return UserLoginVO
	 * @throws BusiException
	 */
	public UserLoginVO visitorLogin(String loginIp) throws BusiException
	{		
		//将对象属性设到VO中，并存入SESSION
		logger.info("游客尝试登陆,登陆IP："+loginIp);
		UserLoginVO vo = new UserLoginVO();
		vo.setLoginId("");
		vo.setUserName("游客");
		vo.setGradeId(new Integer(1));//设定游客的等级为1
		vo.setLoginIp(loginIp);
		vo.setLastLoginIp(loginIp);
		//查询登陆管理员的权限	
		List list = userDAO.getGradePermission(new Integer(1));
		
		TbbsPermission tbbsPermission = null;		
		for(int i=0;i<list.size();i++)
		{			
			tbbsPermission = (TbbsPermission)list.get(i);			
			vo.addPermission(tbbsPermission.getPermissionCode(), tbbsPermission.getPermissionName());
		}
		return vo;
	}
    
    /**
     * AJAX用户登陆.
     * 
     * @param password 密码
     * @param loginId 用户名
     * @param loginIp 登陆IP
     * 
     * @return String AjaxReturn
     * 
     * @throws BusiException
     */
    public String userLoginAjax(String loginId,String password,String loginIp) throws BusiException 
    {
        String ret =  userLoginAjax(loginId,password,loginIp,0,0,0);
        return ret;
    }    
    
	
	/**
     * AJAX用户登陆.
     * 
     * @param password 密码
     * @param validDays 有效期
     * @param loginId 用户名
     * @param hiddenFlag 是否隐身
     * @param userStyle 显示样式
     * @param loginIp 登陆IP
     * 
     * @return String AjaxReturn
     * 
     * @throws BusiException
     */
	public String userLoginAjax(String loginId,String password,String loginIp,Integer validDays,Integer userStyle,Integer hiddenFlag) throws BusiException 
	{
		logger.info("用户 "+loginId+" 尝试以AJAX方式登陆,登陆IP："+loginIp);
        HttpSession session = RequestContext.getContext().getHttpSession();          
        //控制提交限制，15秒内只能提交3次
        Date currentTime = new Date(); //上次提交时间
        Date lastPostTime = (Date)session.getAttribute("lastPostTime"); //上次提交时间
        int  retryTimes = Utility.parseInt((Integer)session.getAttribute("retryTimes"))+1; //重试次数    
        session.setAttribute("retryTimes", retryTimes);
        if(logger.isDebugEnabled())
        {
            logger.debug("上次提交时间："+lastPostTime);
            logger.debug("重试次数："+retryTimes);
            
        }
        if (lastPostTime == null) // 上次提交时间
        {            
            lastPostTime = currentTime;
            session.setAttribute("lastPostTime", currentTime);            
        }
        else
        {
            int betweenSeconds = Utility.getBetweenSeconds(lastPostTime,
                    currentTime);
            if (retryTimes >= 3 && betweenSeconds < 15) // 如果两次提交之间小于15秒
            {  
                throw new BusiException("请不要反复提交登陆动作，请15秒后重新尝试！");
            }
            else if (betweenSeconds > 15)   //重置
            {                
                session.setAttribute("lastPostTime", currentTime);
                session.setAttribute("retryTimes",new Integer(0));
            }
        }
        //验证登陆
		UserLoginVO vo = doUserLogin(loginId,password,loginIp);
        
        vo.setSessionId(session.getId());
        vo.setUserStyle(userStyle);
        vo.setHiddenFlag(hiddenFlag);
        session.setAttribute("USER_LOGIN",vo);
        if(validDays>0)
        {   
            if(logger.isDebugEnabled())
            {
                logger.debug("Cookie有效期："+validDays);
                logger.debug("显示样式："+userStyle);
                logger.debug("用户是否隐身："+hiddenFlag);
            }
            //cookies操作代码  
            HttpServletResponse response = RequestContext.getContext().getHttpResponse();
            ParamUtils.setCookieValue(response, "U_LOGIN_ID", loginId, validDays);
            ParamUtils.setCookieValue(response, "U_PASSWORD", password, validDays);
            ParamUtils.setCookieValue(response, "U_USER_STYLE", String.valueOf(userStyle), validDays);
            ParamUtils.setCookieValue(response, "U_HIDDEN_FLAG", String.valueOf(hiddenFlag), validDays);        
            //cookies操作结束
        }
		session.setAttribute("USER_LOGIN",vo);	//更新SESSION中的登陆用户信息		
        
		Integer userId = vo.getUserId();			
		String ret = AjaxReturn.buildAjaxXml(new String[]{"userId","loginId"}, new String[]{"int","String"}, new Object[]{userId,loginId});
		//移除属性
        session.removeAttribute("lastPostTime");
        session.removeAttribute("retryTimes");
        return ret;
	}
	
	/**
	 * AJAX游客方式登陆
	 * @param loginIp 登陆IP
	 * @return UserLoginVO
	 * @throws BusiException
	 */
	public UserLoginVO visitorLoginAjax(String loginIp) throws BusiException
	{		
		//将对象属性设到VO中，并存入SESSION
		logger.info("游客尝试以AJAX方式登陆,登陆IP："+loginIp);
		UserLoginVO vo = new UserLoginVO();
		vo.setLoginId("");
		vo.setUserName("游客");
		vo.setGradeId(new Integer(1));//设定游客的等级为1
		vo.setLoginIp(loginIp);
		vo.setLastLoginIp(loginIp);
		//查询登陆管理员的权限		
		List list = userDAO.getGradePermission(new Integer(1));
		
		TbbsPermission tbbsPermission = null;		
		for(int i=0;i<list.size();i++)
		{			
			tbbsPermission = (TbbsPermission)list.get(i);			
			vo.addPermission(tbbsPermission.getPermissionCode(), tbbsPermission.getPermissionName());
		}
		HttpSession session = RequestContext.getContext().getHttpSession();			
		session.setAttribute("USER_LOGIN",vo);	//更新SESSION中的登陆用户信息
		return vo;
	}	
	
	
	public void doUserLogout(Date lastLoginTime,String loginIp,Integer userId)
	{		
		userDAO.doLogoutUpdate(lastLoginTime,loginIp, userId);
	}
	
	
	/**
	 * 用户注册验证
	 * @param loginId
	 */
	public void validateLoginId(String loginId) throws BusiException
	{
		if(loginId!=null&&!loginId.equals(""))	//检查登陆ID唯一性
		{
			if(userDAO.load(loginId)!=null)
				throw new BusiException("该用户名已存在！");
		}
	}

	/**
	 * EMAIL验证
	 * @param email
	 */
	public void validateEmail(int userId,String email) throws BusiException
	{
		if(email!=null&&!email.equals(""))	//检查email唯一性
		{
			if(userDAO.countByEmail(userId,email)>0)
				throw new BusiException("该Email已存在！");
		}
	}	
	
	
	/**
	 * 口令强弱等级判定,强度算法有待商榷，功能基本实现
	 * 暂时未使用
	 * @param pass
	 * @return
	 */
	public int rateUserPass(String pass){
		/*
		 * i 值指示口令等级
		 * 0 不合法口令
		 * 1 太短
		 * 2 弱
		 * 3 一般
		 * 4 很好
		 * 5 极佳
		 */
		int i = 0;
		if(Utility.isEmpty(pass)){
			return 0;
		}
		int hasLetter = EncodeString.matcherStr(pass,"[a-zA-Z]","").length();
		int hasNumber = EncodeString.matcherStr(pass,"[0-9]","").length();	
		int passLen = pass.length();
		if(passLen>=6){
			/* 如果仅包含数字或仅包含字母 */
			if((passLen-hasLetter)==0 || (passLen-hasNumber)==0){
				if(passLen<8){
					i = 2;
				}else {
					i = 3;
				}
			}
			/* 如果口令大于6位且即包含数字又包含字母 */
			else if(hasLetter>0 && hasNumber>0){ 
				if(passLen>=10){
					i = 5;
				}else if(passLen>=8){
					i = 4;
				}else{
					i = 3;
				}
			}
			/* 如果既不包含数字又不包含字母 */
			else if(hasLetter==0 && hasNumber==0){
				if(passLen>=7){
					i = 5;
				}else{
					i = 4;
				}
			}
			/* 字母或数字有一方为0 */
			else if(hasNumber==0||hasLetter==0){
				if((passLen-hasLetter)==0 || (passLen-hasNumber)==0){
					i = 2;
				}
				/* 
				 * 字母数字任意一种类型小于6且总长度大于等于6
				 * 则说明此密码是字母或数字加任意其他字符组合而成
				 */
				else{
					if(passLen>8){
						i = 5;
					}else if(passLen==8){
						i = 4;
					}else{
						i = 3;
					}
				}
			}
		}else{ //口令小于6位则显示太短
			if(passLen>0){
				i = 1; //口令太短
			}else{
				i = 0;
			}
		}
		return i;
	}

	public void setUserDAO(IUserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public void setFriendsDAO(IFriendsDAO friendsDAO) {
		this.friendsDAO = friendsDAO;
	}

	public void setRegCounterDAO(IRegCounterDAO regCounterDAO) {
		this.regCounterDAO = regCounterDAO;
	}

	public void setRuleDAO(IRuleDAO ruleDAO) {
		this.ruleDAO = ruleDAO;
	}

	public void setSysInfoDAO(ISysInfoDAO sysInfoDAO) {
		this.sysInfoDAO = sysInfoDAO;
	}

    public void setClassUserDAO(IClassUserDAO classUserDAO)
    {
        this.classUserDAO = classUserDAO;
    }

    public void setClassPermissionDAO(IClassPermissionDAO classPermissionDAO)
    {
        this.classPermissionDAO = classPermissionDAO;
    }	
	
}